//
//  AppBaseRequest.m
//  OA
//
//  Created by Guo Rui on 2017/9/26.
//Copyright © 2017年 GR Harry. All rights reserved.
//

#import "AppBaseRequest.h"
#import <YYModel/YYModel.h>
#import "MessagePackResponseSerializer.h"

#warning 3.配置你的请求信息，比如头部参数等等

//interface config
//#import "AppInterfaceConfig.h"

#define OANetworkDebug YES

@implementation AppBaseRequest

- (instancetype)init {
    self = [super init];
    if (self) {
        //配置你的请求
//        self.baseURL =@"http://192.168.7.143:8080/oaMobile/";
        
        self.baseURL = @"http://testoa.v5time.net/oaMobile/";
        self.requestSerializerType = TFRequestSerializerTypeJSON;
        self.acceptableContentTypesSet = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain",nil];;
        
        NSString *userId = [[[NSUserDefaults standardUserDefaults] objectForKey:@"OANETWORKMANAGERUSER_KEY"] objectForKey:@"userId"];
        if (OANetworkDebug) {
            self.requestHeaders = @{ @"DEBUG" : @"1" ,
                                     @"USERID" : userId ? userId :@""
                                     };
            self.responseSerializerType = TFResponseSerializerTypeJSON;
        }
        else {
            self.responseSerializerType = TFResponseSerializerTypeCustom;
            self.customResponseSerializer = [MessagePackResponseSerializer serializer];
        }
        
        self.timeoutInterval = 20.f;
    }
    return self;
}

- (void)mapResponseJsonObject
{
    if (self.responseJsonObjectMapClassName) {
        Class responseMapClass = NSClassFromString(self.responseJsonObjectMapClassName);
        if (responseMapClass && self.responseJsonObjectMapClassName) {
            NSDictionary *dict = self.responseObject[@"data"];
            self.responseMapObject = [responseMapClass yy_modelWithDictionary:dict];
        }
    }
}

- (void)startRequestWithResponseBlock:(TFRequestResponseBlock)responseBlock
{
    [super startRequestWithResponseBlock:^(__kindof TFRequest * _Nonnull request, id  _Nullable response, NSError * _Nullable error) {
        if (error) {
            // 网络底层的错误
            if (responseBlock) {
                responseBlock(request,response,error);
            }
        }
        else {
            // 接口API错误
            NSInteger code = [[response objectForKey:@"code"] integerValue];
            if (code != 200) {
                NSString *info = [response valueForKey:@"codeInfo"];
                request.error = [NSError errorWithDomain:@"OANetworkErrorDomain" code:code userInfo:@{NSLocalizedDescriptionKey:info?:@"API error"}];
            }
            responseBlock(request, response, nil);
        }
    }];
}



@end
